<!-- 原料详情 -->
<template>
  <el-dialog title="原料详情" width="1000px" :model-value="modelValue" @close="commEvent.onClose" :close-on-click-modal="false">
    <el-form v-if="formData" :model="formData" label-width="90px" class="detail-form">
      <!-- 第一行：盘位号和溶液类型 -->
      <el-row :gutter="40">
        <el-col :span="12">
          <el-form-item label="盘位号：" class="form-item-compact">
            <el-select disabled v-model="formData.positionNo" placeholder="请选择" class="input-unified">
              <el-option v-for="i in 108" :key="i" :label="i" :value="String(i)" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="溶液类型：" class="form-item-compact">
            <el-select v-model="formData.solutionType" placeholder="请选择" class="input-unified">
              <el-option label="溶质" value="0" />
              <el-option label="溶剂" value="1" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 溶质列表（溶液类型为溶质时显示） -->
      <template v-if="formData.solutionType === '0'">
        <div v-for="(solute, index) in formData.solutes" :key="solute.id" class="solute-row">
          <el-row :gutter="40">
            <el-col :span="12">
              <el-form-item label="溶质名称：" class="form-item-compact">
                <el-input v-model="solute.name" placeholder="请输入" class="input-unified" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="溶质浓度：" class="form-item-compact">
                <div class="input-with-actions">
                  <el-input v-model="solute.potency" placeholder="请输入" class="input-unified" />
                  <span class="unit-text">(mg/ml)</span>
                  <el-button link type="danger" class="action-btn delete-btn" @click="commEvent.onDeleteSolute(index)">
                    删除
                  </el-button>
                  <el-button
                    v-if="index === formData.solutes.length - 1"
                    class="action-btn copy-btn"
                    @click="commEvent.onAddSolute"
                  >
                    复制
                  </el-button>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </template>

      <!-- 溶剂信息（溶液类型为溶剂时显示） -->
      <div v-if="formData.solutionType === '1'" class="solvent-row">
        <el-row :gutter="40">
          <el-col :span="24">
            <el-form-item label="溶剂名称：" class="form-item-compact">
              <el-input v-model="formData.solventName" placeholder="请输入" class="input-unified" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="40" class="stock-row">
          <el-col :span="12">
            <el-form-item label="可用量：" class="form-item-compact">
              <div class="input-with-unit">
                <el-input
                  v-model.number="formData.availableStock"
                  type="number"
                  :min="0"
                  :max="maxCapacity"
                  placeholder="请输入"
                  class="input-unified"
                  @blur="commEvent.validateAvailableStock"
                />
                <span class="unit-text">(ml)</span>
                <span class="hint-text">{{ availableStockHint }}</span>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="冻结量：" class="form-item-compact">
              <div class="input-with-unit">
                <el-input disabled v-model="formData.frozenStock" placeholder="请输入" class="input-unified" />
                <span class="unit-text">(ml)</span>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </div>

      <!-- 可用量和冻结量（仅溶质类型显示） -->
      <el-row v-if="formData.solutionType === '0'" :gutter="40" class="stock-row">
        <el-col :span="12">
          <el-form-item label="可用量：" class="form-item-compact">
            <div class="input-with-unit">
              <el-input
                v-model.number="formData.availableStock"
                type="number"
                :min="0"
                :max="maxCapacity"
                placeholder="请输入"
                class="input-unified"
                @blur="commEvent.validateAvailableStock"
              />
              <span class="unit-text">(ml)</span>
              <span class="hint-text">{{ availableStockHint }}</span>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="冻结量：" class="form-item-compact">
            <div class="input-with-unit">
              <el-input disabled v-model="formData.frozenStock" placeholder="请输入" class="input-unified" />
              <span class="unit-text">(ml)</span>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="commEvent.onClose" class="cancel-btn">取消</el-button>
        <el-button type="primary" @click="commEvent.onSave" class="save-btn" :disabled="!isFormValid" v-auth="'biz:sol:modify'">
          保存
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch } from "vue"
import { ElMessage } from "element-plus"
import { modifyPositionData } from "@/api/modules/material"

interface SoluteData {
  id: string
  name: string
  potency: string // 后端字段为potency，不是concentration
}

interface PositionData {
  id: number
  positionNo: string
  solutionType: string // 溶液类型
  materialType: string
  materialName: string
  totalCapacity: number
  availableStock: number // 可用量
  remainingStock: number
  frozenStock: number
  status: "empty" | "normal" | "frozen" | "nodata"
  hasWarning: boolean
  isHighlight: boolean
  remainingPercent: number
  frozenPercent: number
  solutes: SoluteData[]
  solventName?: string // 溶剂名称
  // 后端返回的字段
  no?: number // 盘位号
  type?: number // 类型：0-溶质；1-溶剂
  recipeList?: Array<{ name: string; potency: number }> // 溶液配置集合
  remainAmount?: number // 可用量 (ml)
  freezeAmount?: number // 冻绗量 (ml)
  cap?: number // 总容量 (ml)
}

const props = defineProps({
  modelValue: { type: Boolean, default: false },
  positionData: { type: Object as () => PositionData | null, default: null }
})

const emit = defineEmits(["update:modelValue", "refresh"])

// 表单数据
const formData = ref<PositionData | null>(null)

// 根据后端cap字段获取最大容量限制
const maxCapacity = computed(() => {
  if (!formData.value) return 0
  // 优先使用后端返回的cap字段
  if (formData.value.cap) return formData.value.cap
  if (formData.value.totalCapacity) return formData.value.totalCapacity
  // 如果都没有，根据盘位号判断
  const positionNum = Number(formData.value.positionNo)
  return positionNum <= 54 ? 50 : 150
})

// 可用量提示文本
const availableStockHint = computed(() => {
  return `最大容量：${maxCapacity.value}ml`
})

// 表单验证
const isFormValid = computed(() => {
  if (!formData.value) return false

  // 检查溶液类型
  if (!formData.value.solutionType) return false

  // 根据溶液类型进行不同的验证
  if (formData.value.solutionType === "0") {
    // 溶质类型：检查溶质数据
    const hasEmptySolute = formData.value.solutes.some(s => !s.name || !s.potency)
    if (hasEmptySolute) return false
  } else if (formData.value.solutionType === "1") {
    // 溶剂类型：检查溶剂名称
    if (!formData.value.solventName) return false
  }

  // 检查可用量
  if (!formData.value.availableStock) return false

  // 检查可用量不能超过最大容量
  if (formData.value.availableStock > maxCapacity.value) return false

  return true
})

// 监听positionData变化
watch(
  () => props.positionData,
  newData => {
    if (newData) {
      // 处理后端返回的数据结构
      const recipeList = newData.recipeList || []
      const solutes =
        recipeList.length > 0
          ? recipeList.map((item: any, index: number) => ({
              id: `s-${index + 1}`,
              name: item.name || "",
              potency: String(item.potency || "")
            }))
          : [{ id: `s-1`, name: "", potency: "" }]

      formData.value = {
        ...newData,
        positionNo: String(newData.no || newData.positionNo || ""),
        solutionType: String(newData.type ?? newData.solutionType ?? ""),
        availableStock: newData.remainAmount ?? newData.availableStock ?? 0,
        frozenStock: newData.freezeAmount ?? newData.frozenStock ?? 0,
        totalCapacity: newData.cap ?? newData.totalCapacity ?? 0,
        solutes: solutes,
        // 如果是溶剂类型，从第一个recipeList项获取溶剂名称
        solventName: newData.type === 1 && recipeList.length > 0 ? recipeList[0].name : ""
      }
    }
  },
  { immediate: true, deep: true }
)

// 监听盘位号变化，自动验证可用量
watch(
  () => formData.value?.positionNo,
  () => {
    if (formData.value?.availableStock) {
      // 延迟执行验证，确保maxCapacity已更新
      setTimeout(() => {
        commEvent.validateAvailableStock()
      }, 0)
    }
  }
)

// 事件
const commEvent = {
  // 关闭弹窗
  onClose: () => {
    emit("update:modelValue", false)
  },

  // 验证可用量
  validateAvailableStock: () => {
    if (!formData.value) return

    const value = Number(formData.value.availableStock)
    const max = maxCapacity.value

    if (value < 0) {
      formData.value.availableStock = 0
      ElMessage.warning("可用量不能为负数")
      return
    }

    if (value > max) {
      formData.value.availableStock = max
      ElMessage.warning(`当前盘位最大容量为${max}ml，已自动调整`)
      return
    }
  },

  // 新增溶质（复制）
  onAddSolute: () => {
    if (!formData.value) return

    const newId = `s-${Date.now()}`
    formData.value.solutes.push({
      id: newId,
      name: "",
      potency: ""
    })
  },

  // 删除溶质
  onDeleteSolute: (index: number) => {
    if (!formData.value) return

    if (formData.value.solutes.length <= 1) {
      ElMessage.warning("至少保留一个溶质")
      return
    }

    formData.value.solutes.splice(index, 1)
  },

  // 保存
  onSave: async () => {
    if (!formData.value) return

    // 校验数据
    if (!formData.value.solutionType) {
      ElMessage.warning("请选择溶液类型")
      return
    }

    // 根据溶液类型进行不同的验证
    if (formData.value.solutionType === "0") {
      // 溶质类型：检查溶质数据
      const hasEmptySolute = formData.value.solutes.some(s => !s.name || !s.potency)
      if (hasEmptySolute) {
        ElMessage.warning("请完善溶质信息")
        return
      }
    } else if (formData.value.solutionType === "1") {
      // 溶剂类型：检查溶剂名称
      if (!formData.value.solventName) {
        ElMessage.warning("请输入溶剂名称")
        return
      }
    }

    if (!formData.value.availableStock) {
      ElMessage.warning("请输入可用量")
      return
    }

    // 验证可用量不超过最大容量
    if (formData.value.availableStock > maxCapacity.value) {
      ElMessage.warning(`可用量不能超过${maxCapacity.value}ml`)
      return
    }

    try {
      // 根据溶液类型构建不同的数据结构
      const requestData: any = {
        no: Number(formData.value.positionNo),
        type: Number(formData.value.solutionType),
        remainAmount: formData.value.availableStock
      }

      if (formData.value.solutionType === "0") {
        // 溶质类型：发送溶质列表
        requestData.recipeList = formData.value.solutes.map(s => ({
          name: s.name,
          potency: String(s.potency)
        }))
      } else if (formData.value.solutionType === "1") {
        // 溶剂类型：发送溶剂名称
        requestData.recipeList = [
          {
            name: formData.value.solventName,
            potency: "0" // 溶剂浓度固定为0
          }
        ]
      }

      // 调用后端接口修改数据
      await modifyPositionData(requestData)

      ElMessage.success("保存成功")
      emit("update:modelValue", false)
      emit("refresh")
    } catch (error) {
      console.error("保存失败:", error)
      ElMessage.error("保存失败，请稍后重试")
    }
  }
}
</script>

<style lang="scss" scoped>
// 统一输入框和下拉框宽度
.input-unified {
  width: 100%;
}
.detail-form {
  position: relative;
  padding: 0 10px;
  .form-item-compact {
    margin-bottom: 20px;
    :deep(.el-form-item__label) {
      font-size: 14px;
      font-weight: 500;
      line-height: 1.5;
      color: #303133;
    }
    :deep(.el-form-item__content) {
      display: flex;
      width: 100%;
    }
  }

  // 第一行样式优化
  .el-row:first-child {
    margin-bottom: 8px;
    .form-item-compact {
      margin-bottom: 16px;
    }
  }
  .solute-row {
    margin-bottom: 0;
    .input-with-actions {
      display: flex;
      gap: 8px;
      align-items: center;
      width: 100%;
      .input-unified {
        flex: 1;
        min-width: 0;
      }
      .unit-text {
        flex-shrink: 0;
        margin-left: 4px;
        font-size: 14px;
        color: #606266;
        white-space: nowrap;
      }
      .action-btn {
        flex-shrink: 0;
        padding: 8px 15px;
        margin-left: 4px;
        font-size: 14px;
        border-radius: 4px;
        &.delete-btn {
          padding: 8px 15px;
          color: #f56c6c;
          &:hover {
            color: #f56c6c;
            background-color: #fef0f0;
          }
        }
        &.copy-btn {
          color: #ffffff;
          background: #722ed1;
          border: none;
          &:hover {
            background: #9254de;
          }
          &:active {
            background: #531dab;
          }
        }
      }
    }
  }
  .solvent-row {
    margin-bottom: 0;
    .stock-row {
      margin-top: 10px;
      .input-with-unit {
        display: flex;
        flex-wrap: wrap;
        gap: 8px;
        align-items: center;
        width: 100%;
        .input-unified {
          flex: 1;
          min-width: 0;
        }
        .unit-text {
          flex-shrink: 0;
          margin-left: 4px;
          font-size: 14px;
          color: #606266;
          white-space: nowrap;
        }
        .hint-text {
          flex-basis: 100%;
          margin-top: 4px;
          font-size: 12px;
          line-height: 1.5;
          color: #909399;
        }
      }
    }
  }
  .stock-row {
    margin-top: 10px;
    .input-with-unit {
      display: flex;
      flex-wrap: wrap;
      gap: 8px;
      align-items: center;
      width: 100%;
      .input-unified {
        flex: 1;
        min-width: 0;
      }
      .unit-text {
        flex-shrink: 0;
        margin-left: 4px;
        font-size: 14px;
        color: #606266;
        white-space: nowrap;
      }
      .hint-text {
        flex-basis: 100%;
        margin-top: 4px;
        font-size: 12px;
        line-height: 1.5;
        color: #909399;
      }
    }
  }
}

// 底部按钮区域
.dialog-footer {
  display: flex;
  gap: 12px;
  justify-content: center;
  padding: 10px 0;
  .cancel-btn {
    min-width: 80px;
    padding: 8px 20px;
  }
  .save-btn {
    min-width: 80px;
    padding: 8px 20px;
    background: #722ed1;
    border-color: #722ed1;
    &:hover:not(:disabled) {
      background: #9254de;
      border-color: #9254de;
    }
    &:active:not(:disabled) {
      background: #531dab;
      border-color: #531dab;
    }
    &:disabled {
      color: #00000040;
      cursor: not-allowed;
      background: #d9d9d9;
      border-color: #d9d9d9;
    }
  }
}

// 调整dialog样式
:deep(.el-dialog) {
  .el-dialog__header {
    padding: 16px 24px;
    border-bottom: 1px solid #e8e8e8;
    .el-dialog__title {
      font-size: 16px;
      font-weight: 500;
      color: #000000;
    }
  }
  .el-dialog__body {
    padding: 24px;
    padding-bottom: 60px;
  }
  .el-dialog__footer {
    padding: 12px 24px;
    border-top: 1px solid #e8e8e8;
  }
}
</style>
